package org.rency.crawler.fetch.handler.impl;

import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.rency.crawler.common.CrawlerConstants;
import org.rency.crawler.common.enums.ReturnCode;
import org.rency.crawler.common.exception.CrawlerException;
import org.rency.crawler.common.exception.CrawlerIllegalException;
import org.rency.crawler.common.helper.GeneratorHelper;
import org.rency.crawler.common.helper.ValidatorHelper;
import org.rency.crawler.domain.FetchExtension;
import org.rency.crawler.domain.FetchResponse;
import org.rency.crawler.domain.state.FetchStatus;
import org.rency.crawler.fetch.handler.AbstractFetchHandler;
import org.rency.crawler.fetch.helper.FetchCarrier;
import org.rency.crawler.fetch.helper.FetchHelper;
import org.rency.crawler.fetch.repository.FetchExtRepository;
import org.rency.crawler.fetch.repository.MetaResourceRepository;
import org.rency.crawler.fetch.service.url.URLService;
import org.rency.crawler.plugins.url.NormalizeUrl;
import org.springframework.stereotype.Component;

/**
 * 描述: ${TODO}<br>
 * 最近修改时间:2017/11/22 11:24<br>
 *
 * @author CaiyuRen
 * @version V1.0
 * @since 2017/11/22 11:24
 */
@Component
public class FetchValidHandler extends AbstractFetchHandler {

  @Resource
  private MetaResourceRepository metaResourceRepository;

  @Resource
  private FetchExtRepository     fetchExtRepository;

  @Resource
  private URLService             urlService;

  @Override
  protected String getHandlerName() {
    return "参数校验";
  }

  @Override
  protected void onHandler(FetchCarrier carrier) throws CrawlerException {
    FetchResponse response = this.validate(carrier);
    carrier.setResponse(response);
    if(response.getSuccess()){
      this.fillProperty(carrier);
    }
    carrier.getFetchState().setFsStatus(response.getSuccess() ? FetchStatus.SUCCESS : FetchStatus.FAILED);
  }

  private FetchResponse validate(FetchCarrier carrier){
    try{
      ValidatorHelper.notNull(carrier,"抓取载体");
      ValidatorHelper.notNull(carrier.getRequest(),"抓取请求");
      if(StringUtils.isEmpty(carrier.getRequest().getHostAddr())){
        NormalizeUrl normalizeUrl = urlService.normalize(carrier.getRequest().getFetchUri());
        ValidatorHelper.notNull(normalizeUrl,"URI地址无效");
        carrier.getRequest().setHostAddr(normalizeUrl.getHost());
      }
    }catch(CrawlerIllegalException e){
      logger.error("{}参数校验失败.",this.getHandlerName(),e);
      return FetchResponse.fail(ReturnCode.ILLEGAL_VALID,e.getDetailMessage());
    }
    return FetchResponse.success();
  }

  private void fillProperty(FetchCarrier carrier){
    if(StringUtils.isBlank(carrier.getRequest().getFetchNo())){
      String fullURL = FetchHelper
          .appendParam2URL(carrier.getRequest().getFetchUri(),carrier.getRequest().getParameter());
      carrier.getRequest().setFetchNo(GeneratorHelper.genHashCode(fullURL));
    }

    if(StringUtils.isBlank(carrier.getRequest().getFetchHost())){
      carrier.getRequest().setFetchHost(GeneratorHelper.genHashCode(carrier.getRequest().getHostAddr()));
    }
    FetchExtension extension = carrier.getExtension();
    if(extension == null){
      extension = fetchExtRepository.find(carrier.getRequest().getFetchNo());
      if(extension == null){
        extension = new FetchExtension();
        extension.setMachineIP(CrawlerConstants.LOCATION_MACHINE_IP);
        extension.setMaxRetryTimes(metaResourceRepository.getFetchRetryTimes());
        extension.setFetchDepth(metaResourceRepository.getFetchDepth());
        extension.setFetchWeight(metaResourceRepository.getFetchWeight());
        fetchExtRepository.save(carrier.getRequest().getFetchNo(),extension);
      }
      carrier.setExtension(extension);
    }
    if(StringUtils.isBlank(extension.getMachineIP())){
      extension.setMachineIP(CrawlerConstants.LOCATION_MACHINE_IP);
    }
  }

}
